#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <regex.h>


static char* substr(const char*str, unsigned start, unsigned end)
{
    unsigned n = end - start;
    static char stbuf[256];
    strncpy(stbuf, str + start, n);
    stbuf[n] = 0;
    return stbuf;
}


int main()
{
    regex_t     reg;
    regmatch_t  pm[10];
    char        buff[128];
    int         ret;
    int         i;

    regcomp(&reg, "a", 0);
    strcpy(buff, "this file is a file");

    ret = regexec(&reg, buff, 10, pm, 0);
    if (ret == REG_NOMATCH){
        regfree(&reg);
        printf("no match\n");
    } else if (ret < 0) {
        regfree(&reg);
        fprintf(stderr, "regcom error\n");
    }else{
        regfree(&reg);
        for (i = 0; i < 10 && pm[i].rm_so != -1; ++ i) {
            printf(" str = |%s| $%2d:from %2d to %2d: str: %s\n", buff, i, pm[i].rm_so, pm[i].rm_eo, substr(buff, pm[i].rm_so, pm[i].rm_eo));
        }
    }

    regcomp(&reg, "s", 0);
    strcpy(buff, "this file is a file");

    ret = regexec(&reg, buff, 10, pm, 0);
    if (ret == REG_NOMATCH){
        regfree(&reg);
        printf("no match\n");
    } else if (ret < 0) {
        regfree(&reg);
        fprintf(stderr, "regcom error\n");
    }else{
        regfree(&reg);
        for (i = 0; i < 10 && pm[i].rm_so != -1; ++ i) {
            printf(" str = |%s| $%2d:from %2d to %2d: str: %s\n", buff, i, pm[i].rm_so, pm[i].rm_eo, substr(buff, pm[i].rm_so, pm[i].rm_eo));
        }
    }
    return 0;
}
